package com.bjpowernode.crm.web.listener;

import com.alibaba.fastjson.JSONObject;
import com.bjpowernode.crm.setting.eneity.DicValue;
import com.bjpowernode.crm.setting.service.DicService;
import com.bjpowernode.crm.setting.service.impl.DicServiceImpl;
import com.bjpowernode.crm.util.ServiceFactory;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.*;

/**
 * 全局作用域监听器
 */
public class SysInitListener implements ServletContextListener {
    private DicService dicService;
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        //全局作用域初始化时执行
        ServletContext application=sce.getServletContext();
        //获取到dicService对象
        dicService= (DicService) WebApplicationContextUtils.getWebApplicationContext(application).getBean("dicService");
        //调用service和dao查询字典信息
        Map<String,List<DicValue>> map=dicService.getAll();
        //将字典信息解析为全局作用域对象中的key-value形式
        Set<String> set=map.keySet();
        for (String key:set){
            application.setAttribute(key,map.get(key));
        }
        //=============================================>
        //数据字典初始化完毕后，将属性配置文件中的阶段和可能性以键值对的形式存储在map中，再存储到上下文中
        Map<String,String> pMap=new HashMap<>();
        ResourceBundle bundle=ResourceBundle.getBundle("Stage2Possibility");
        Enumeration<String> keyEnum=bundle.getKeys();
        while (keyEnum.hasMoreElements()){
            //阶段
            String key=keyEnum.nextElement();
            //可能性
            String value=bundle.getString(key);
            pMap.put(key,value);
        }
        //将map转为json字符串
        String json=JSONObject.toJSONString(pMap);
        application.setAttribute("pMap",json);
    }
}
